package com.hundsun.cprs.yyt.service.trade.service.impl;

import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.hundsun.cprs.yyt.service.account.domain.AccountStat;
import com.hundsun.cprs.yyt.service.account.service.AccountDailyLimitCacheService;
import com.hundsun.cprs.yyt.service.account.service.AccountService;
import com.hundsun.cprs.yyt.service.account.service.AccountStatService;
import com.hundsun.cprs.yyt.service.common.dto.FundBatchRequest;
import com.hundsun.cprs.yyt.service.common.dto.UserAccountDTO;
import com.hundsun.cprs.yyt.service.common.enums.EnumFundBidCode;
import com.hundsun.cprs.yyt.service.common.service.RemoteTradeFundService;
import com.hundsun.cprs.yyt.service.common.service.RemoteUserService;
import com.hundsun.cprs.yyt.service.dilivery.domain.DiliveryAddress;
import com.hundsun.cprs.yyt.service.dilivery.service.DiliveryAddressService;
import com.hundsun.cprs.yyt.service.goods.dto.GoodsInfo;
import com.hundsun.cprs.yyt.service.goods.service.GoodsService;
import com.hundsun.cprs.yyt.service.goods.service.GoodsSkuService;
import com.hundsun.cprs.yyt.service.order.domain.OrderItem;
import com.hundsun.cprs.yyt.service.order.dto.OrderInfo;
import com.hundsun.cprs.yyt.service.order.enums.EnumDeliveryMethod;
import com.hundsun.cprs.yyt.service.order.enums.EnumOrderSNCode;
import com.hundsun.cprs.yyt.service.order.enums.EnumsOrderStatus;
import com.hundsun.cprs.yyt.service.order.service.OrderService;
import com.hundsun.cprs.yyt.service.trade.domain.ReturnGoodsFlow;
import com.hundsun.cprs.yyt.service.trade.domain.TradeCancelFlow;
import com.hundsun.cprs.yyt.service.trade.dto.EntrustDeliveryRequest;
import com.hundsun.cprs.yyt.service.trade.enums.*;
import com.hundsun.cprs.yyt.service.trade.service.ReturnGoodsFlowService;
import com.hundsun.cprs.yyt.service.trade.service.TradeCancelFlowService;
import com.hundsun.cprs.yyt.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;

import com.hundsun.cprs.yyt.common.base.BaseService;
import com.hundsun.cprs.yyt.common.enums.EnumBusinessCode;
import com.hundsun.cprs.yyt.common.exception.ServiceCodeException;
import com.hundsun.cprs.yyt.common.exception.ServiceException;
import com.hundsun.cprs.yyt.service.rabbit.RoutingKeyConstants;
import com.hundsun.cprs.yyt.service.system.enums.EnumBussinessParam;
import com.hundsun.cprs.yyt.service.system.service.BusinessParamHelper;
import com.hundsun.cprs.yyt.service.system.service.BussinessParamService;
import com.hundsun.cprs.yyt.service.trade.dao.TradeEntrustDao;
import com.hundsun.cprs.yyt.service.trade.domain.TradeEntrust;
import com.hundsun.cprs.yyt.service.trade.domain.query.TradeEntrustQuery;
import com.hundsun.cprs.yyt.service.trade.service.TradeEntrustService;
import org.springframework.util.Assert;

@Service
public class TradeEntrustServiceImpl extends BaseService implements TradeEntrustService {

    @Autowired
    private TradeEntrustDao tradeEntrustDao;
    @Autowired
    private BussinessParamService systemParam;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private AccountDailyLimitCacheService accountDailyLimitCacheService;
    @Autowired
    private BussinessParamService bussinessParamService;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @Autowired
    private OrderService orderService;
    @Autowired
    private GoodsSkuService goodsSkuService;
    @Autowired
    private RemoteTradeFundService remoteTradeFundService;
    @Autowired
    private RemoteUserService remoteUserService;
    @Autowired
    private DiliveryAddressService diliveryAddressService;

    @Autowired
    private AccountStatService accountStatService;
    @Autowired
    private TradeCancelFlowService cancelFlowService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private ReturnGoodsFlowService returnGoodsFlowService;
    @Autowired
    private GoodsService goodsService;

    @Value("${trade.entrust.audit.enable:false}")
    private String tradeEntrustAuditEnable;//挂售单上报手动审核配置，默认不开启，即自动上报

    @Value("${trade.entrust.daliy.limit.enable:true}")
    private String tradeEntrustDaliyLimitEnable;//用户每日挂售规则限制是否开启，默认开启

    @Override
    @Transactional
    public void createEntrust(TradeEntrust entrust) {
        entrust.setEntrustNo(tradeEntrustDao.getEntrustNoFromSequence());
        entrust.setEntrustStatus(EnumTradeEntrustStatus.INIT.getStatus());
        entrust.setStatus(EnumTradeStatus.INIT.getStatus());
        if (entrust.getEntrustFrom() == null) {
            //默认为都是会员挂单
            entrust.setEntrustFrom(EnumEntustFrom.FROM_USER.getCode());
        }
        //先更新挂售申请次数统计
        tradeAccountStatTime(entrust);
        //设置新老用户标签
        setTradeEntrustTag(entrust);
        if (entrust.getEntrustTag() == null) {
            //默认都是老用户标签
            entrust.setEntrustTag(EnumEntustTag.OLD_USER.getCode());
        }
        if (StringUtils.equals(EnumEntustBSType.SELL.getCode().toString(), entrust.getEntrustBs())) {
            // TODO:获取全局交易手续费及综合管理费比例
            entrust.setCommissionRate(BusinessParamHelper.getIntValue(systemParam, EnumBussinessParam.COMMISSION_RATE));
            entrust.setManagementRate(BusinessParamHelper.getIntValue(systemParam, EnumBussinessParam.MANAGEMENT_RATE));
        } else {
            entrust.setCommissionRate(0);
            entrust.setManagementRate(0);
        }
        entrust.setCommissionFund(BigDecimal.ZERO.longValue());
        entrust.setManagementFund(BigDecimal.ZERO.longValue());
        entrust.setBusinessFund(BigDecimal.ZERO.longValue());
        entrust.setTotalBusinessFund(BigDecimal.ZERO.longValue());
        entrust.setGainBusinessFund(BigDecimal.ZERO.longValue());
        entrust.setBusinessAmount(BigDecimal.ZERO.longValue());
        //由于审核功能，此处直接将挂售时间置为申请时间，审核上报时不再修改挂售时间
        entrust.setEntrustTime(new Date());
        tradeEntrustDao.insert(entrust);
    }
    
    @Override
    public void createAndCommitEntrust(TradeEntrust entrust) {
        DefaultTransactionDefinition defintion = new DefaultTransactionDefinition();
        defintion.setPropagationBehavior(Propagation.REQUIRES_NEW.value());
        defintion.setIsolationLevel(Isolation.READ_COMMITTED.value());
        TransactionStatus status = transactionTemplate.getTransactionManager().getTransaction(defintion);
        try{
            createEntrust(entrust);
            transactionTemplate.getTransactionManager().commit(status);
        } catch(Exception e) {
            transactionTemplate.getTransactionManager().rollback(status);
            throw e;
        }
        
        try {
            if (entrust.isSell() && tradeEntrustAuditEnable.equals("false")){
                //卖单受手动审核配置限制，开启手动审核之后，则不再自动上报
                entrust(entrust);
            }else if (entrust.isBuy()){
                //买单不受手动审核限制，不管是否开启手动审核配置，仍然是自动上报
                entrust(entrust);
            }
        } catch (Exception e) {
            logger.warn("自动上报挂单失败",e);
        }
    }

    @Override
    public void selectByPage(TradeEntrustQuery query) {
        List<TradeEntrust> result = tradeEntrustDao.selectByQuery(query);
        query.compatible(result);
    }

    @Override
    public TradeEntrust getTradeEntrustById(Long id) {
        // TODO Auto-generated method stub
        return tradeEntrustDao.selectByPrimaryKey(id);
    }

    @Override
    public void entrust(TradeEntrust entrust) {
        if (EnumTradeEntrustStatus.INIT.getStatus() != entrust.getEntrustStatus()) {
            throw new ServiceCodeException(EnumBusinessCode.BUSSINESS_1700);
        }
        // 针对卖单，处理每日用户委售限制规则
        //过滤掉平台委售的单子
        if (tradeEntrustDaliyLimitEnable.equals("true") && entrust.isSell() && entrust.isFromUser()){
            //1.挂单时间间隔限制
            validateTimePeriod(entrust.getUserId());
            //2.每日挂单数量限制
            if (!accountDailyLimitCacheService.isUserSellAmountMeetsLimit(entrust.getUserId(),1L)){
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1517.getErrorNo(),EnumBusinessCode.BUSINESS_1517.getErrorInfo());
            }
            //3.每日挂单金额限制
            if (!accountDailyLimitCacheService.isUserSellMoneyMeetsLimit(entrust.getUserId(),entrust.getEntrustAmount()*entrust.getEntrustPrice())){
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1518.getErrorNo(),EnumBusinessCode.BUSINESS_1518.getErrorInfo());
            }
        }
        // 通过MQ方式通知匹配中心处理
        rabbitTemplate.convertAndSend(RoutingKeyConstants.YYT_TRADE_ENTRUST_COMMIT, entrust);
    }

    @Override
    @Transactional(isolation=Isolation.READ_COMMITTED)
    public TradeEntrust updateEntrustStatus(TradeEntrust tradeEntrust , Integer expectEntrustStatus) {
        int count = tradeEntrustDao.updateEntrustStatus(tradeEntrust,expectEntrustStatus);
        if (count == 0) {
            throw new ServiceException("状态已被更新");
        }
        TradeEntrust newRecord = tradeEntrustDao.selectByPrimaryKey(tradeEntrust.getId());
        return newRecord;
    }

    protected void tradeAccountStatTime(TradeEntrust tradeEntrust){
        //更新账户的委售次数，上报成功就算
        //只有委卖方向才进行委售成功次数的统计
        if (tradeEntrust.getEntrustBs().equals(EnumEntustBSType.SELL.getCode().toString())){
            AccountStat accountStat = new AccountStat();
            accountStat.setUserId(tradeEntrust.getUserId());
            accountStat.setTrusteTime(1L);
            accountStatService.updateAccountStat(accountStat);
        }
    }

    private void setTradeEntrustTag(TradeEntrust entrust){
        if (EnumEntustFrom.FROM_USER.getCode() == entrust.getEntrustFrom()) {
            //会员委托,则设置委托标签
            boolean isNewUser = accountStatService.isNewUser(entrust.getUserId());
            if (isNewUser) {
                entrust.setEntrustTag(EnumEntustTag.NEW_USER.getCode());
            }else{
                entrust.setEntrustTag(EnumEntustTag.OLD_USER.getCode());
            }
        }
    }


    @Override
    public void batchUpdateEntrust(List<TradeEntrust> entrusts) {
        if (entrusts == null || entrusts.isEmpty()) {
            return;
        }
        tradeEntrustDao.batchUpdate(entrusts);
    }

    @Override
    public List<TradeEntrust> selectByList(TradeEntrustQuery query) {
        query.onlyReturnList();
        return tradeEntrustDao.selectByQuery(query);
    }

    @Override
    public void updateEntrustOrder(TradeEntrust tradeEntrust) {
        tradeEntrustDao.updateByPrimaryKeySelective(tradeEntrust);
    }

    @Override
    public int getCommitedQuantitySumByGoodsId(Integer goodsId) {
        String count = tradeEntrustDao.getCommitedQuantitySumByGoodsId(goodsId.longValue());
        if (count == null){
            return 0;
        }else{
            return Integer.parseInt(count);
        }
    }
    
    @Override
	public long getTradeQuantitySumByQuery(TradeEntrustQuery query) {
    	query.onlyReturnList();
    	query.setEntrustStatusArray(new Integer[] {EnumTradeEntrustStatus.INIT.getStatus(),EnumTradeEntrustStatus.COMMITED.getStatus(),
    											   EnumTradeEntrustStatus.PART_DEALT.getStatus()});
		return tradeEntrustDao.getTradeQuantitySumByQuery(query);
	}

    protected void validateTimePeriod(Long userId){
        int timeProidLimit = BusinessParamHelper.getIntValue(bussinessParamService,EnumBussinessParam.TIME_INTERVAL_BETWEEN_SELL,60);
        if (timeProidLimit == 0) {
            return;
        }
        //1.获取该用户最新的挂售单信息
        TradeEntrust lastedEntrust = tradeEntrustDao.getUserLastedTradeEntrust(userId);
        if (lastedEntrust != null){
            //2.比较上个委托单的委托时间和当前时间之间的差值是否符合两次挂售的时间间隔限制
            Float difference = DateUtil.countMinites(lastedEntrust.getGmtCreate(),new Date());
            if (difference.intValue() < timeProidLimit){
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1519.getErrorNo(),EnumBusinessCode.BUSINESS_1519.getErrorInfo());
            }
        }
    }

    @Override
    public TradeEntrust getTradeEntrustByOrderSn(String orderSn) {
        return tradeEntrustDao.getTradeEntrustByOrderSn(orderSn);
    }

    @Override
    public Map<String, Long> getUserDaliyEntrustTimeAndMoney(TradeEntrustQuery query) {
        Map<String,Long> dataMap = new HashMap<>();
        Long entrustTimes = 0L;
        Long entrustMoney = 0L;
        query.setEntrustBs(EnumEntustBSType.SELL.getCode().toString());
        query.setStartDate(DateUtil.getBeginOfDay(new Date()));
        query.setEndDate(DateUtil.getEndOfDay(new Date()));
        List<TradeEntrust> tradeEntrustList = this.selectByList(query);
        if (!tradeEntrustList.isEmpty()){
            for (TradeEntrust tradeEntrust:tradeEntrustList){
                entrustTimes ++;
                entrustMoney += tradeEntrust.getEntrustAmount() * tradeEntrust.getEntrustPrice();
            }
        }
        dataMap.put("entrustTimes",entrustTimes);
        dataMap.put("entrustMoney",entrustMoney);
        return dataMap;
    }

    /*@Override
    @Transactional
    public void returnGoods(TradeEntrust tradeEntrust) {
        OrderInfo order = orderService.selectOrderInfoByOrderSn(tradeEntrust.getOrderSn());
        //1.将订单状态改为已退货，并设置订单项里的退货信息
        updateOrderStatus(tradeEntrust,order);
        //2.将挂售单状态修改为已完成
        updateTrusteOrderStatus(tradeEntrust);
        //3.退货之后更新库存
        updateSkuStock(order);
        //4.退货需要退配额：退货数量 * 配额单价
        returnQuota(order);
        //5.退货之后给买家打款，卖家扣款
        returnBackMoney(tradeEntrust,order);
    }*/

    @Override
    @Transactional
    public void returnGoods(TradeEntrust tradeEntrust) {
        OrderInfo order = orderService.selectOrderInfoByOrderSn(tradeEntrust.getOrderSn());
        //生成退货申请审核记录
        ReturnGoodsFlow flow = new ReturnGoodsFlow();
        flow.setEntrustId(tradeEntrust.getId());
        flow.setEntrustNo(tradeEntrust.getEntrustNo());
        flow.setFundAccount(tradeEntrust.getFundAccount());
        flow.setGoodsCode(tradeEntrust.getGoodsCode());
        flow.setReturnAmount(tradeEntrust.getSurplusEntrustAmount());
        flow.setUserId(tradeEntrust.getUserId());
        if (order != null){
            flow.setOrderId(order.getId());
            //计算退款金额
            OrderItem item = order.getOrderItems().get(0);
            Long returnMoney = new BigDecimal(item.getPrice()).multiply(new BigDecimal(flow.getReturnAmount())).longValue();
            flow.setReturnFundAmount(returnMoney);
            //获取退货数量和配额单价
            Long returnAmount = flow.getReturnAmount();
            Long quotaAmount = item.getQuotaAmount();
            //计算要退回的配额数量
            Long returnQuotaAmount = new BigDecimal(returnAmount).multiply(new BigDecimal(quotaAmount)).longValue();
            flow.setReturnQuoteAmount(returnQuotaAmount);
            //填充商品名称
            flow.setGoodsName(item.getGoodsName());
            flow.setQuotaId(item.getPayQuotaId());
        }else {
            GoodsInfo goodsInfo = goodsService.selectGoodsInfoById(tradeEntrust.getGoodsId().intValue());
            if (goodsInfo != null){
                flow.setGoodsName(goodsInfo.getGoodsName());
            }
        }
        returnGoodsFlowService.createReturnGoodsFlow(flow);
    }

    @Override
    @Transactional
    public void applyDeliveryGoods(TradeEntrust tradeEntrust, EntrustDeliveryRequest request) {
        //1.将订单状态改为待发货，并设置提货地址信息
        updateOrderStatusAndDiliveryInfo(tradeEntrust,request);
        //2.将挂售单状态修改为已完成
        updateTrusteOrderStatus(tradeEntrust);
    }

    protected void updateOrderStatus(TradeEntrust tradeEntrust,OrderInfo orderInfo){
        if (orderInfo != null){
            //更新订单状态
            orderInfo.setStatus(EnumsOrderStatus.RETURN.getStatus());
            orderInfo.setCompleteDate(new Date());
            //更新订单项内的退货数量和已成数量
            for (OrderItem orderItem:orderInfo.getOrderItems()){
                Long saledAmount = Math.abs(tradeEntrust.getBusinessAmount());
                orderItem.setReturnedQuantity(tradeEntrust.getEntrustAmount() - saledAmount);
                orderItem.setShippedQuantity(saledAmount);
            }
            orderService.updateOrder(orderInfo);
        }
    }

    protected void updateTrusteOrderStatus(TradeEntrust tradeEntrust){
        //更新委托单的大类状态和小类状态
        tradeEntrust.setStatus(EnumTradeStatus.DEALT.getStatus());
        tradeEntrust.setEntrustStatus(EnumTradeEntrustStatus.DEALT.getStatus());
        this.updateEntrustOrder(tradeEntrust);
    }

    protected void updateSkuStock(OrderInfo orderInfo){
        //更新商品的预占库存和实际库存
        if (orderInfo != null){
            //更新sku的库存
            OrderItem orderItem = orderInfo.getOrderItems().get(0);
            int outMount = orderItem.getQuantity();//预占库存直接减掉
            int stock = orderItem.getQuantity() - orderItem.getReturnedQuantity().intValue();//退货时实际扣减库存是总量减去退货的数量
            goodsSkuService.deductGoodsStock(orderItem.getSkuId(),outMount,stock);
        }
    }

    protected void returnQuota(OrderInfo orderInfo){
        if (orderInfo != null){
            //获取退货数量和配额单价
            OrderItem item = orderInfo.getOrderItems().get(0);
            Long returnAmount = item.getReturnedQuantity();
            Long quotaAmount = item.getQuotaAmount();
            //计算要退回的配额数量
            Long returnQuotaAmount = new BigDecimal(returnAmount).multiply(new BigDecimal(quotaAmount)).longValue();
            accountService.addQuota(orderInfo.getUserId(),returnQuotaAmount,"退货返还配额");
        }
    }

    protected void returnBackMoney(TradeEntrust tradeEntrust,OrderInfo order){
        if (order == null){
            throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1006.getErrorNo(),EnumBusinessCode.BUSINESS_1006.getErrorInfo());
        }
        //计算退货金额
        Long saledAmount = Math.abs(tradeEntrust.getBusinessAmount());
        Long returnBackMoney = tradeEntrust.getEntrustPrice()*(tradeEntrust.getEntrustAmount()- saledAmount);
        //流水描述
        String memo = MessageFormat.format("[{0}]挂售单退货收入",order.getOrderItems().get(0).getGoodsName());
        FundBatchRequest request = FundBatchRequest.builder("system", EnumOrderSNCode.getOrderFundSN(order.getSn(), EnumOrderSNCode.FUND_IN),memo);
        if (returnBackMoney != null && returnBackMoney > 0){
            //扣除卖家的退款金额
            UserAccountDTO sellerInfo = remoteUserService.getUserDetailByUserId(order.getSellerId());
            if (sellerInfo == null) {
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1001.getErrorNo(),"卖家信息状态异常");
            }
            request.addTask(sellerInfo.getFundAccount(), EnumFundBidCode.CFUND_170201, order.getSn(), returnBackMoney,"买家订单退货扣款");
            //给买家打款
            request.addTask(order.getFundAccount(), EnumFundBidCode.CFUND_170102, order.getSn(), returnBackMoney);
            remoteTradeFundService.batchExecute(request);
        }
    }

    protected void updateOrderStatusAndDiliveryInfo(TradeEntrust tradeEntrust,EntrustDeliveryRequest request){
        //获取订单信息
        OrderInfo orderInfo = orderService.selectOrderInfoByOrderSn(tradeEntrust.getOrderSn());
        if (orderInfo != null){
            //更新订单状态和订单关联的提货地址信息
            orderInfo.setDiliveryId(request.getDiliveryId());
            orderInfo.setStatus(EnumsOrderStatus.WAIT_DELIVERY.getStatus());
            orderInfo.setDeliveryType(request.getDeliveryType());
            //自提信息
            if (request.getDeliveryType().equals(EnumDeliveryMethod.SELFGET.ordinal())) {
                orderInfo.setConsignee(request.getSeleGetName());
                orderInfo.setPhone(request.getSelfGetPhone());
                orderInfo.setSelfGetTime(DateUtil.strToDate(request.getSelfGetTime(), "yyyy-MM-dd"));
            }
            //更新订单的提货地址
            alterOrderInfoAddress(orderInfo,request);
            //更新订单项内的已成数量
            for (OrderItem orderItem:orderInfo.getOrderItems()){
                orderItem.setShippedQuantity(Math.abs(tradeEntrust.getBusinessAmount()));
            }
            orderService.updateOrder(orderInfo);
        }
    }
    protected void alterOrderInfoAddress(OrderInfo orderInfo,EntrustDeliveryRequest request){
        DiliveryAddress diliveryAddress = diliveryAddressService.selectAddressDetailByAddressId(request.getDiliveryId());
        if (diliveryAddress != null){
            String addresss = new StringBuffer()
                    .append(diliveryAddress.getProvinceAddress())
                    .append(diliveryAddress.getMunicipalAddress())
                    .append(diliveryAddress.getCountyAddress())
                    .append(diliveryAddress.getDiliveryAddress())
                    .toString();
            orderInfo.setAddress(addresss);

            //物流方式
            if (request.getDeliveryType().equals(EnumDeliveryMethod.DELIVERY.ordinal())) {
                orderInfo.setConsignee(diliveryAddress.getConsigneeName());
                orderInfo.setPhone(diliveryAddress.getPhone());
            }
        }
    }

    @Override
    public void selectAuditByPage(TradeEntrustQuery query) {
        List<TradeEntrust> entrustList = tradeEntrustDao.selectAuditByPage(query);
        query.compatible(entrustList);
    }

    @Override
    public void auditEntrust(String[] entrustIds) {
        for (int i =0;i<entrustIds.length;i++){
            TradeEntrust tradeEntrust = tradeEntrustDao.selectByPrimaryKey(Long.parseLong(entrustIds[i]));
            this.entrust(tradeEntrust);
        }
    }

    @Override
    public void cancelEntrust(Long entrustNo) {
        Assert.notNull(entrustNo, "委托单编号必填");

        TradeEntrust entrust = tradeEntrustDao.selectByEntrustNo(entrustNo);
        if (entrust == null) {
            throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1520);
        }
        if (!entrust.isTrading()) {
            throw new ServiceCodeException(EnumBusinessCode.BUSSINESS_1702);
        }

        TradeCancelFlow flow = new TradeCancelFlow();
        flow.setEntrustId(entrust.getId());
        flow.setEntrustNo(entrust.getEntrustNo());
        flow.setCancelStatus(EnumEntrustCancelStatus.COMMITED.getCode());
        cancelFlowService.createCancelFlow(flow);

        //通过MQ推送撤单请求
        rabbitTemplate.convertAndSend(RoutingKeyConstants.YYT_TRADE_ENTRUST_CANCEL, flow);
    }
}
